import json

from django.shortcuts import render
from django.shortcuts import redirect
import pandas as pd

def login(requests):
    if requests.method == "GET":
        return render(requests, 'login.html')
    username = requests.POST['username']
    print('用户名：',username)
    pwd = requests.POST['pwd']
    print('密码：', username)
    tbl_datas = pd.read_excel('t_user.xlsx')
    datas = list(tbl_datas.loc[:, 'username'])
    if username in datas:
        i = datas.index(username)
        real_name = tbl_datas.loc[i, 'names']
        passwd = tbl_datas.loc[i, 'password']
        if pwd == str(passwd):
            rep = redirect('/index/')
            rep.set_cookie("is_login",True)
            real_name = json.dumps(real_name)
            rep.set_cookie("username",real_name)
            return rep
        else:
            info = '密码错误'
    else:
        info = "用户名不存在"
    return render(requests, 'error.html', {"info": info})


def showIndex(requests):
    login_status = requests.COOKIES.get("is_login")
    real_name = json.loads(requests.COOKIES.get("username"))
    print("真是姓名",real_name)
    if not login_status:
       return redirect('/login/')
    return render(requests,'index.html',{"real_name":real_name})